package other.system.client.apitool;

import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.http.CommonData;
import com.rkhd.platform.sdk.http.CommonHttpClient;
import com.rkhd.platform.sdk.http.HttpResult;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.service.CacheService;
import com.rkhd.platform.sdk.service.CustomConfigService;
import other.system.client.util.ResultBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: FSSC财务共享提供推送客户
 * @Author: 黎炎松
 * @Date: 2024/6/12 10:21
 */
public class FsscClientUtils {
    private static String BASE_API = "https://fsscgc.tcl.com/fssc-api"; // 正式域名
    //private static String BASE_API = "http://fsscapp.tcl.com:8082/test-api"; // 测试域名
    private static String GET_TOKEN_URL = BASE_API + "/auth/getAppToken"; // 获取token
    public static String ADD_UP_ACCOUNT_URL = BASE_API + "/fssc-data/syncCustomer/syncCustomerForBill"; // 新增、修改客户
    private static final Logger logger = LoggerFactory.getLogger();
    // k3 信息配置
    public static Map<String, String> fsscConfig = new HashMap<>();

    static {
        try {
            CustomConfigService instance = CustomConfigService.instance();
            fsscConfig = instance.getConfigSet("fsscConfig");
            if (fsscConfig == null) {
                fsscConfig = new HashMap<>();
            }
        } catch (CustomConfigException e) {
            throw new RuntimeException(e);
        }
    }


    public static void main(String[] args) throws CustomConfigException {
        new FsscClientUtils().getToken();
    }

    /**
     * 发送get请求
     * @param paramsMap
     * @param reqUrl
     * @return
     */
    public static ResultBody sendGet(Map<String, Object> paramsMap, String reqUrl) {

        //Boolean set = CacheService.instance().set("testKey", "testValue");
        //String testKey = CacheService.instance().get("testKey");
        //System.out.println("testKey = " + testKey);

        // 拼接 URL
        String token = getToken();
        String params = "";
        for (String key : paramsMap.keySet()) {
            if (params == "") {
                params = "?" + key + "=" + paramsMap.get(key);
            } else {
                params += "&" + key + "=" + paramsMap.get(key);
            }
        }

        // 进行转码
        params = params.replaceAll("&", "%26");
        params = params.replaceAll(" ", "%20");

        CommonData build = CommonData.newBuilder().callString(reqUrl + params)
                .callType("GET")
                .header("token", token)
                .build();
        HttpResult execute = CommonHttpClient.instance().execute(build);
        String result = execute.getResult();
        System.out.println("result = " + result);
        JSONObject response = JSONObject.parseObject(result);
        Integer code = response.getInteger("code");
        String msg = response.getString("msg");
        if (code != 100) {
            ResultBody.error(msg);
        }
        JSONObject data = response.getJSONObject("data");
        return ResultBody.success(data);
    }

    /**
     * 发送post请求
     * @param reqData
     * @param reqUrl
     * @return
     */
    public static ResultBody sendPost(JSONObject reqData, String reqUrl) {

        String token = getToken();
        CommonData build = CommonData.newBuilder().callString(reqUrl)
                .callType("POST")
                .header("appToken", token)
                .body(JSONObject.toJSONString(reqData))
                .formType("")
                .build();
        HttpResult execute = CommonHttpClient.instance().execute(build);
        String result = execute.getResult();
        logger.info("result: " + result);
        JSONObject response = JSONObject.parseObject(result);
        Boolean success = response.getBoolean("success");
        JSONObject retData = response.getJSONObject("data");
        if (!success) {
            String errorMsg = retData.getString("errorMsg");
            return ResultBody.error(errorMsg);
        }

        Integer retCode = retData.getInteger("retCode");
        String retMsg = retData.getString("retMsg");
        if (retCode != 9999) {
            return ResultBody.error(retMsg);
        }
        String billNumber = retData.getString("billNumber");
        return ResultBody.success(billNumber);
    }

    /**
     * token 有效期：4小时
     * @return
     */
    public static String getToken() {

        String appId = fsscConfig.getOrDefault("appId", "gc_sys");
        String appSecret = fsscConfig.getOrDefault("appSecret","9ea71f87be6f3ff0");
        String reqParams = String.format("?appId=%s&appSecret=%s", appId, appSecret);

        // 发送请求
        CommonData build = CommonData.newBuilder().callString(GET_TOKEN_URL + reqParams)
                .callType("GET")
                .build();

        HttpResult execute = CommonHttpClient.instance().execute(build);
        String result = execute.getResult();
        JSONObject response = JSONObject.parseObject(result);
        Integer code = response.getInteger("code");
        if (!Objects.equals(code, 0)) {
            System.out.println("result = " + result);
            return null;
        }
        String token = response.getString("data");
        return token;
    }


}
